import axios from 'axios'
import { Message, Loading } from 'element-ui'
import $constant from '@/utils/open/constant'


/******* 创建文件上传axios实例 **********/
const uploadService = axios.create({
  baseURL: $constant.ctx,
  timeout: 30000 //文件上传请求时间

});

let loading;        //定义loading变量
function startLoading() {    //使用Element loading-start 方法
  loading = Loading.service({
    lock: true,
    text: '上传中……',
    background: 'rgba(0, 0, 0, 0.3)'
  })
}
function endLoading() {    //使用Element loading-close 方法
  loading.close()
}
let needLoadingRequestCount = 0

export function showFullScreenLoading() {
  if (needLoadingRequestCount === 0) {
    startLoading()
  }
  needLoadingRequestCount++
}

export function tryHideFullScreenLoading() {
  if (needLoadingRequestCount <= 0) return
  needLoadingRequestCount--
  if (needLoadingRequestCount === 0) {
    endLoading()
  }
}

/*********request拦截器==>对请求参数做处理**********/
uploadService.interceptors.request.use(config => {
  //打开预加载
  if (config.showLoading) {
    showFullScreenLoading();
  }
  config.headers['Content-Type'] = 'multipart/form-data;charset=UTF-8'
  config.headers['Authorization'] = window.localStorage.getItem('authToken') ? window.localStorage.getItem('authToken') : ''
  return config
}, error => {
  Message({
    message: error,
    type: 'error'
  })
  Promise.reject(error)
})

/****** respone拦截器==>对响应做处理 ******/
uploadService.interceptors.response.use(

  response => {
    //关闭预加载
    if (response.config.showLoading) {
      tryHideFullScreenLoading();
    }
    if (response.status === 200) {
      return response.data
    } else {
      Message({
        message: response.statusText,
        type: 'error'
      })
    }
  },
  error => {  //响应错误处理
    console.log('error')
    console.log(error)
    console.log(JSON.stringify(error))

    let text = JSON.parse(JSON.stringify(error)).response.status === 404
      ? '404'
      : '网络异常，请重试'
    Message({
      message: text,
      type: 'warning'
    })
    try {
      //关闭预加载
      if (response.config.showLoading) {
        tryHideFullScreenLoading();
      }
      return Promise.reject(error)
    } catch (err) {

    }

    return Promise.reject(error)
  }
);

export default uploadService;
